package com.monkeygroup.mygoplus.view.entrance.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyAlertDialog;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.user.vo.PersonalNomalInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by cumt on 2017/3/12.
 */

public class RegitsterCodeFragment extends Fragment implements View.OnClickListener {

    public static RegitsterCodeFragment getInstance(String phone,String type,String loginFlg) {
        RegitsterCodeFragment f = new RegitsterCodeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("phone", phone);
        bundle.putString("type", type);
        bundle.putString("loginFlg", loginFlg);//判断是否为三方注册

        f.setArguments(bundle);

        return f;
    }


    private View mView;

    private Activity activity;
    //头部
    private TextView txtTitle;
    private ImageView imgBack;

    // Fragment管理对象
    private FragmentManager manager;
    private FragmentTransaction ft;

    private TextView txtPhone;

    private EditText et_now_pwd;
    //
    private String code;


    //倒计时
    private TimeCount time;
    private TextView code_time;

    //請求參數
    private Map<String, String> params;
    private HttpModel httpModel,checkVerify;

    private String type,phone,loginFlg;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        activity = this.getActivity();
        manager = getFragmentManager();

        if (mView == null) {

            mView = inflater.inflate(R.layout.fragment_code, container, false);

            params = new HashMap<>();
            initView();
            initListener();
            initRequest();



            httpModel.startRequest();
        }
        return mView;
    }

    private void initView() {

        txtTitle =  (TextView)mView.findViewById(R.id.txt_title);
        txtTitle.setText("臨時密碼");
        imgBack =  (ImageView) mView.findViewById(R.id.img_back);

        code_time = (TextView) mView.findViewById(R.id.code_time);
        time = new TimeCount(30000, 1000);//构造CountDownTimer对象


        txtPhone =  (TextView)mView.findViewById(R.id.txt_phone);

         phone = getArguments().getString("phone");
         type = getArguments().getString("type");
        loginFlg = getArguments().getString("loginFlg");
        txtPhone.setText(phone);

        PersonalNomalInfo vo = new PersonalNomalInfo();
        vo.setMobile(phone);
        LocalInfo.saveUserInfo(activity,vo);

        et_now_pwd =  (EditText) mView.findViewById(R.id.et_now_pwd);
        params.put("mobile",phone);

    }

    private void initListener() {

        mView.findViewById(R.id.btn_code_next).setOnClickListener(this);

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getFragmentManager().popBackStack();
            }
        });


        et_now_pwd.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {



                if (et_now_pwd.length()==6) {

                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(et_now_pwd.getWindowToken(), 0) ;


                }
                else{


                }

            }

            @Override
            public void afterTextChanged(Editable s) {




            }
        });

    }

    private void initRequest() {

        //发送短信
        httpModel = new HttpModel(RequestUrl.baseUrl + RequestUrl.verifyUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {

                if (!VilidateUtil.isSuccess(resultCode)) {

//                    MyAlertDialog dialog = new MyAlertDialog(activity, resultMsg, 0);
//                    dialog.show(activity, resultMsg, 0);

                  //  code=(String)data;
                } else {
                    time.start();


                }
            }
        }, true);
        //短信验证
        checkVerify= new HttpModel(RequestUrl.baseUrl + RequestUrl.checkVerifyUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {

                if (!VilidateUtil.isSuccess(resultCode)) {

//                    MyAlertDialog dialog = new MyAlertDialog(activity, resultMsg, 0);
//                    dialog.show(activity, resultMsg, 0);

                } else {
                    Map<String,String> result = (HashMap)data;
                    if(result!=null && result.get("message").equals("验证码输入正确")){
                        if("1".equals(type)){
                            FindPasswordFragment register = FindPasswordFragment.getInstance(phone);
                            ft = manager.beginTransaction();
                            //当前的fragment会被RegisterFragment替换
                            ft.replace(R.id.fragment_container, register);
                            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                            ft.addToBackStack(null);
                            ft.commit();

                        }
                        else{
                            SetPasswordFragment register = new SetPasswordFragment();
                            ft = manager.beginTransaction();
                            //当前的fragment会被RegisterFragment替换
                            ft.replace(R.id.fragment_container, register);
                            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                            ft.addToBackStack(null);
                            ft.commit();
                        }
                    }
                    else if(result!=null && result.get("message").equals("验证码输入错误")){
                        MyAlertDialog dialog = new MyAlertDialog(activity, "验证码输入错误", "");
                        dialog.show(activity, "验证码输入错误", 3);

                    }
                    else if(result!=null && result.get("message").equals("验证码失效")){
                        MyAlertDialog dialog = new MyAlertDialog(activity, "验证码失效", "");
                        dialog.show(activity, "验证码失效", 3);

                    }

                }
            }
        }, true);



    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_code_next:
                Log.e("loginFlgloginFlg",loginFlg);
                if(loginFlg.equals("thirdLogin")){
                    RegisterCompletefragment registerComplete = new RegisterCompletefragment();
                    ft = manager.beginTransaction();
                    //当前的fragment会被RegisterFragment替换
                    ft.replace(R.id.fragment_container, registerComplete);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    ft.addToBackStack(null);
                    ft.commit();
                }else{
                    //判断输入是否正确
                    if(!"".equals(String.valueOf(et_now_pwd.getText()))){
                        params.put("verifyCode",String.valueOf(et_now_pwd.getText()));
                        checkVerify.startRequest();
                    }
                    else{
                        MyAlertDialog dialog = new MyAlertDialog(activity, "请输入验证码", "");
                        dialog.show(activity, "请输入验证码", 1);
                    }

                }

                break;

        }

    }


    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }
        @Override
        public void onFinish() {//计时完毕时触发
            code_time.setText("重新验证");
            code_time.setClickable(true);
            code_time.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    httpModel.startRequest();

                }
            });
          //  code_time.setTextColor(getResources().getColor(R.color.font_gray_III));
        }
        @Override
        public void onTick(long millisUntilFinished){//计时过程显示
            code_time.setClickable(false);
            code_time.setText(millisUntilFinished / 1000 + "秒");
           // code_time.setTextColor(getResources().getColor(R.color.font_black));
        }
    }
}
